<?php
declare (strict_types=1);

namespace app\v1\controller;

use app\BaseController;
use app\model\Notice;
use app\Request;
use app\model\Config;
use app\model\GoodsOrder;
use app\model\User;
use app\model\UserAccount;
use app\model\UserLayer;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use thans\jwt\facade\JWTAuth;
use tool\Random;

class UserController extends BaseController
{
	protected $middleware = ['Login' => ['except' => ['login', 'register', 'getAccountText','getUserInfoText']]];
	
	/**
	 * 登录
	 * @param Request $request
	 */
	function login(Request $request)
	{
		$code = $request->post('code');
		$client = new Client();
		$wechat = Config::getFieldByName('wechat', 'value');
		$wechat = json_decode($wechat);
		$wechat = $client->get("https://api.weixin.qq.com/sns/jscode2session?appid=$wechat->appid&secret=$wechat->secret&js_code=$code&grant_type=authorization_code");
		$wechat = $wechat->getBody()->getContents();
		$wechat = json_decode($wechat);
		if (!isset($wechat->openid)) {
			writeJson(0, $wechat->errmsg);
		}
		//  存储登录态
		$user = User::where(['openid' => $wechat->openid])->find();
		if ($user) {
			if ($user->status == 'hidden') {
				writeJson(0, '账号被禁止');
			}
			$user->prevtime = $user->logintime;
			$user->logintime = time();
			$user->loginip = $request->ip();
			$user->save();
		} else {
			do {
				$invite_code = Random::alnum(7);
			} while (User::where(['invite_code' => $invite_code])->find());
			
			$user = User::create([
				'logintime' => time(),
				'loginip' => $request->ip(),
				'jointime' => time(),
				'joinip' => $request->ip(),
				'openid' => $wechat->openid,
				'nickname' => '游客' . rand(1000000, 9999999),
				'avatar' => '/assets/img/avatar.png',
				'status' => 'normal',
				'invite_code' => $invite_code
			]);
		}
		
		$token = JWTAuth::builder(['user_id' => $user->id]);
		writeJson(['user' => $user, 'token' => 'Bearer ' . $token]);
		
	}
	
	/**
	 * 注册
	 * @param Request $request
	 * @return void
	 * @throws GuzzleException
	 */
	function register(Request $request)
	{
		$nickname = $request->post('nickname');
		$invite_code = $request->post('invite_code');
		$teamname = $request->post('teamname');
		$code = $request->post('code');
		$mobile_code = $request->post('mobile_code');
		
		if (!$nickname || !$invite_code || !$teamname || !$code|| !$mobile_code) {
			writeJson(0, '缺少参数');
		}
		
		// 检测用户名、昵称、邮箱、手机号是否存在
		if (User::getByTeamname($teamname)) {
			writeJson(0, '团队用户名已存在');
		}
		if (User::getByNickname($nickname)) {
			writeJson(0, '用户昵称已存在');
		}
		$parent = User::getByInviteCode($invite_code);
		if (!$parent) {
			writeJson(0, '邀请码填写错误');
		}
		$client = new Client();
		$wechat = Config::getFieldByName('wechat', 'value');
		$wechat = json_decode($wechat);
		$auth = $client->get("https://api.weixin.qq.com/sns/jscode2session?appid=$wechat->appid&secret=$wechat->secret&js_code=$code&grant_type=authorization_code");
		$auth = $auth->getBody()->getContents();
		$auth = json_decode($auth);
		if (!isset($auth->openid)) {
			writeJson(0, $auth->errmsg);
		}
		$access_token = $client->get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$wechat->appid&secret=$wechat->secret");
		$access_token = $access_token->getBody()->getContents();
		$access_token = json_decode($access_token);
		if (!isset($access_token->access_token)){
			writeJson(0,$access_token->errmsg);
		}
		$access_token = $access_token->access_token;
		
		$phone_info = $client->post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token",[
			'body' => json_encode([
				'code' => $mobile_code,
			])
		]);
		$phone_info =  $phone_info->getBody()->getContents();
		$phone_info = json_decode($phone_info);
		if ($phone_info->errcode!=0){
			writeJson(0,$phone_info->errmsg);
		}
		$mobile = $phone_info->phone_info->phoneNumber;
		$user = User::getByOpenid($auth->openid);
		
	
		if ($user) {
			if ($user->level != 0) {
				writeJson(0, '此微信已经是代理,请直接登录');
			}
			//如果是游客直接升级为店长
			$user->level = 1;
			$user->teamname = $teamname;
			$user->nickname = $nickname;
			$user->mobile = $mobile;
			$user->pid = $parent->id;
			$user->save();
		} else {
			do {
				$invite_code = Random::alnum(7);
			} while (User::where(['invite_code' => $invite_code])->find());
			
			$data = [
				'teamname' => $teamname,
				'avatar' => '/assets/img/avatar.png',
				'nickname' => $nickname,
				'mobile' =>$mobile,
				'jointime' => time(),
				'joinip' => $request->ip(),
				'logintime' => time(),
				'loginip' => $request->ip(),
				'prevtime' => time(),
				'status' => 'normal',
				'invite_code'=> $invite_code,
				'openid' => $auth->openid,
				'level' => 1, //直接升级为店长
				'pid' => $parent->id,
			];
			$user = User::create($data);
		}
		
		//增加直推关系
		$position = UserLayer::where( 'user_id', $parent->id)->select();
		$data['user_id'] = $user->id;
		$data['pid'] = $parent->id;
		$data['layer'] = 1;
		UserLayer::create($data);
		if (!$position->isEmpty()) {
			foreach ( $position as $v ) {
				$data=[
					'user_id'=>$user->id,
					'pid'=>$v->pid,
					'layer'=>$v->layer+1,
				];
				UserLayer::create( $data );
			}
		}
		
		$token = JWTAuth::builder(['user_id' => $user->id]);
		writeJson(['user' => $user, 'token' => 'Bearer ' . $token]);
	}
	
	/**
	 * 用户信息
	 * @param Request $request
	 * @return void
	 */
	function getUserInfo(Request $request)
	{
		$open_switch = Config::getFieldByName('open_switch', 'value');
		$row = User::findOrFail($request->user_id);
		$row->open_switch = $open_switch;
		writeJson($row);
	}
	
	/**
	 * 编辑用户信息
	 * @param Request $request
	 * @return void
	 */
	function editUserInfo(Request $request)
	{
		$avatar = $request->post('avatar','');
		$nickname = $request->post('nickname','');
		$truename = $request->post('truename','');
		$mobile = $request->post('mobile','');
		$birthday = $request->post('birthday','');
		$wechat = $request->post('wechat','');
		$city = $request->post('city','');
		$user = User::findOrFail($request->user_id);
		if ($avatar) {
			$user->avatar = $avatar;
		}
		if ($nickname) {
			$user->nickname = $nickname;
		}
		if ($truename) {
			$user->truename = $truename;
		}
		if ($mobile) {
			$user->mobile = $mobile;
		}
		if ($birthday) {
			$user->birthday = $birthday;
		}
		if ($wechat) {
			$user->wechat = $wechat;
		}
		if ($city) {
			$user->city = $city;
		}
		$user->save();
		writeJson();
	}
	
	/**
	 * 用户账户信息
	 * @param Request $request
	 * @return void
	 */
	function getUserAccount(Request $request)
	{
		$rows = UserAccount::where(['user_id'=>$request->user_id])->select();
		writeJson($rows);
	}
	
	/**
	 * 添加账号
	 * @param Request $request
	 * @return void
	 */
	function addUserAccount(Request $request)
	{
		$ali_name = $request->post('ali_name','');
		$ali_account = $request->post('ali_account','');
		$wechat_name = $request->post('wechat_name','');
		$wechat_account = $request->post('wechat_account','');
		$bank_truename = $request->post('bank_truename','');
		$bank_card = $request->post('bank_card','');
		$bank = $request->post('bank','');
		$bank_name = $request->post('bank_name','');
		$aliAccount = UserAccount::where(['user_id'=>$request->user_id,'type'=>1])->find();
		$wechatAccount = UserAccount::where(['user_id'=>$request->user_id,'type'=>2])->find();
		$bankAccount = UserAccount::where(['user_id'=>$request->user_id,'type'=>2])->find();
		if (!empty($ali_name)&&!empty($ali_account)){
			$data=['user_id'=>$request->user_id,'type'=>1,'name' => $ali_name, 'account' => $ali_account];
			if ($aliAccount){
				$aliAccount->save($data);
			}else{
				UserAccount::create($data);
			}
		}
		
		if (!empty($wechat_name)&&!empty($wechat_account)){
			$data=['user_id'=>$request->user_id,'type'=>2,'name' => $wechat_name, 'account' => $wechat_account];
			if ($wechatAccount){
				$wechatAccount->save($data);
			}else{
				UserAccount::create($data);
			}
		}
		
		if (!empty($bank_truename)&&!empty($bank_card)&&!empty($bank)&&!empty($bank_name)){
			$data=['user_id'=>$request->user_id,'type'=>3,'name' => $bank_truename, 'account' => $bank_card,'bank'=>$bank,'bank_name'=>$bank_name];
			if ($bankAccount){
				$bankAccount->save($data);
			}else{
				UserAccount::create($data);
			}
		}
		writeJson();
	}
	
	/**
	 * 获取二维码
	 * @return void
	 * @throws GuzzleException
	 */
	function getQRCode(Request $request)
	{
		$client = new Client();
		$invite_code = User::getFieldById($request->user_id,'invite_code');
		$wechat = Config::getFieldByName('wechat', 'value');
		$wechat = json_decode($wechat);
		$access_token = $client->get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$wechat->appid&secret=$wechat->secret");
		$access_token = $access_token->getBody()->getContents();
		
		$access_token = json_decode($access_token)->access_token;
		
		$wxacode = $client->post("https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token",[
			'body' => json_encode([
				'path' => "pages/invitelogin/invitelogin?invite_code=$invite_code",
				'env_version'=>env('APP_DEBUG', true)?'trial':'release'
			])
		]);
		$res = $wxacode->getBody()->getContents();
	
		writeJson(['qrcode'=>base64_encode($res),'invite_code'=>$invite_code]);
	}
	
	/**
	 * 未读数
	 * @param Request $request
	 * @return void
	 * @throws \think\db\exception\DbException
	 */
	function getTip(Request $request)
	{
		$data = [
			'status_1'=>GoodsOrder::where(['user_id'=>$request->user_id,'status'=>0])->count(), //待付款
			'status_2'=>GoodsOrder::where(['user_id'=>$request->user_id,'status'=>1])->count(), //待发货
			'status_3'=>GoodsOrder::where(['user_id'=>$request->user_id,'status'=>2])->count(), //待收货
			'status_4'=>GoodsOrder::where(['user_id'=>$request->user_id,'status'=>3])->count(), //完后
			'status_5'=>GoodsOrder::where(['user_id'=>$request->user_id])->whereIn('status',[6,7,8])->count(), //售后
			'status_6'=>GoodsOrder::where(['user_id'=>$request->user_id,'status'=>6])->count(), //售后审核
			'status_7'=>Notice::where(['user_id'=>$request->user_id,'read'=>0])->count(),//消息
		];
		writeJson($data);
	}
	
	/**
	 * 获取账户文字
	 * @return void
	 */
	function getAccountText()
	{
		$data = [
			'text_1'=>'账户信息',
			'text_2'=>'姓名',
			'text_3'=>'支付宝账号',
			'text_4'=>'绑定支付宝',
			'text_5'=>'账户信息',
			'text_6'=>'姓名',
			'text_7'=>'微信账号',
			'text_8'=>'绑定微信',
			'text_9'=>'银行卡信息',
			'text_10'=>'姓名',
			'text_11'=>'银行卡号',
			'text_12'=>'银行名称',
			'text_13'=>'开户行',
			'text_14'=>'绑定银行卡',
		];
//		$data = [
//			'text_1'=>'',
//			'text_2'=>'',
//			'text_3'=>'',
//			'text_4'=>'',
//			'text_5'=>'',
//			'text_6'=>'',
//			'text_7'=>'',
//			'text_8'=>'',
//			'text_9'=>'',
//			'text_10'=>'',
//			'text_11'=>'',
//			'text_12'=>'',
//			'text_13'=>'',
//			'text_14'=>'',
//		];
		writeJson($data);
	}
	
	function getUserInfoText()
	{
		$data = [
			'text_1'=>'*修改昵称',
			'text_2'=>'请输入您的昵称',
			'text_3'=>'*姓名',
			'text_4'=>'请输入您的姓名',
			'text_5'=>'*手机号',
			'text_6'=>'请输入你的手机号',
			'text_7'=>'微信号',
			'text_8'=>'请输入您的微信号',
			'text_9'=>'出生日期',
			'text_10'=>'请选择您的出生日期',
			'text_11'=>'所在城市',
			'text_12'=>'请输入您的所在城市',
		];
//		$data = [
//			'text_1'=>'',
//			'text_2'=>'',
//			'text_3'=>'',
//			'text_4'=>'',
//			'text_5'=>'',
//			'text_6'=>'',
//			'text_7'=>'',
//			'text_8'=>'',
//			'text_9'=>'',
//			'text_10'=>'',
//			'text_11'=>'',
//			'text_12'=>'',
//		];
		writeJson($data);
	}
}
